import React, { useEffect, useRef, useState } from "react";
import { Swiper, Image, DotLoading, SpinLoading } from "antd-mobile";
import { queryNewsLatest, queryNewsBefore } from "./../../service/api";
import "./index.less";

// 在JSX里面想使用图片，导入在使用。不能直接在img写相对路径。 CSS里面的图被处理过
// let img = require('@/assets/favicon.png')
import img from "@/assets/timg.jpg";

const monthMap = {
  1: "一月",
  2: "二月",
  3: "三月",
  4: "四月",
  5: "五月",
  6: "六月",
  7: "七月",
  8: "八月",
  9: "九月",
  10: "十月",
  11: "十一月",
  12: "十二月",
};


/* 20241227 字符串转年月日数组  */
const dayFormat = (dataString) => {
  return dataString.match(/^(\d{4})(\d{2})(\d{2})$/).slice(1);
}


const Home = (props) => {
  const { navigate } = props;

  /* 创建所需要的状态 */
  let [today, setToday] = useState(() => {
    let date = new Date().toLocaleString().split(" ")[0].replace(/\//g, '');
    return dayFormat(date);
  });
  let [bannerData, setBannerData] = useState([]);
  let [newsList, setNewsList] = useState([]);
  let loadMoreRef = useRef(null);

  //跳转到详情页面
  const handlerDetail = (id) => {
    navigate(`/details/${id}`);
  };

  /* 获取页面所需数据 */
  const getData = async () => {
    try {

      // 获取今日新闻列表
      const { top_stories, date, stories } = await queryNewsLatest();
      setBannerData(top_stories);
      setToday(dayFormat(date));

      // 获取昨日新闻列表
      const res = await queryNewsBefore(data);
      let storiesMap = stories.map(item => {
        item.date = res.data;
        return item;
      });
      setNewsList(storiesMap);
    } catch (error) {
      console.log('查询数据失败...', error);
    }
  };

   /* 上滑加载更多列表 */
  const loadMoreData = async () => {
    let obj = new IntersectionObserver(async change => {
      let { isIntersecting } = change[0];
      if (isIntersecting) {
        try {
          debugger
          const time = newsList.length && newsList[newsList.length - 1].date;
          const res = await queryNewsBefore(time);
          setNewsList([...newsList, ...res.stories]);
        } catch (error) {
          console.log('获取以往新闻失败 ...', err);
        }
      }
    });

    let loadMoreBox = loadMoreRef.current;
    obj.observe(loadMoreBox);

    // 组件释放时候执行
    return () => {
      debugger
      obj.unobserve(loadMoreBox);
      obj = null;
    }
  }

  /* 组件第一次渲染完毕后：从服务器获取数据 */
  useEffect(() => {
    getData();
  }, []);


  /* 组件卸载后 & 重新渲染执行 */
  useEffect(() => {
    return loadMoreData();
  }, []);

  return (
    <div className="home-page">
      <div className="header-view">
        <div className="info">
          <p>
            <span>{today[2]}</span>
            <span>{monthMap[today[1]]}</span>
          </p>
          <h2 className="title">早点休息</h2>
        </div>
        <div className="avatar-view">
          <img src={img} />
        </div>
      </div>

      <div className="banner-view">
        {bannerData.length > 0 ? (
          <Swiper autoplay={true} loop={true}>
            {bannerData.map((item) => {
              return (
                <Swiper.Item key={item.id}>
                  <div
                    className="banner-item"
                    onClick={handlerDetail.bind(null, item.id)}
                  >
                    <Image
                      src={item.image}
                      alt=""
                      lazy
                    />
                    <div className="banner-cont">
                      <h2>{item.title}</h2>
                      <p className="author-info">
                        <span>{item.hint}</span>
                      </p>
                    </div>
                  </div>
                </Swiper.Item>
              );
            })}
          </Swiper>
        ) : <SpinLoading color='primary' />}
      </div>
      <div className="content-view">
        {
          newsList.length > 0 ? <>
            {
              newsList.map(item => {
                return (
                  <div className="item-view" key={item.id} onClick={handlerDetail.bind(null, item.id)}>
                    <div className="content-list-cont">
                      <h3>{item.title}</h3>
                      <p>{item.hint}</p>
                    </div>
                    <div className="content-list-img">
                      <Image
                        src={item.images[0]}
                        alt=""
                        lazy
                      />
                    </div>
                  </div>
                )
              })
            }
            <div>
            </div>
          </> : <SpinLoading color='primary' />
        }
        <div className="loadMore-view" ref={loadMoreRef} style={{ display: newsList.length > 0 ? 'block' : 'none' }}>
          <DotLoading />
          <span>加载中</span>
        </div>
      </div>
    </div>
  );
};

export default Home;
